package com.rs.admin.controller.sy;


import com.rs.admin.common.RespResult;
import com.rs.admin.mapper.MenuInfoMapper;
import com.rs.admin.module.MenuInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//@Api(tags = "菜单操作")
@RestController
@RequestMapping("/menu")
public class MenuInfoController {


    @Resource
    MenuInfoMapper menuInfoMapper;

//    @ApiOperation("新增")
    @PostMapping("/save")
    public RespResult save(@RequestBody MenuInfo menu) {

        menuInfoMapper.insert(menu);

        return RespResult.buildSuccess();
    }


//    @ApiOperation("列表")
    @GetMapping("/list")
    public RespResult list() {

        List<MenuInfo> infos = menuInfoMapper.selectList(null);

        List<MenuInfo> menu = builderTree(infos);

        return RespResult.buildSuccess(menu);

    }


    public List<MenuInfo> builderTree(List<MenuInfo> infos) {

        Map<Integer, List<MenuInfo>> map = infos.stream().collect(Collectors.groupingBy(MenuInfo::getPid));
        List<MenuInfo> menuInfo = map.get(0);

        for (MenuInfo info : menuInfo) {
            info.setChild(getChild(info.getId(), map));
        }

        return menuInfo;
    }


    public List<MenuInfo> getChild(Integer pid, Map<Integer, List<MenuInfo>> map) {

        List<MenuInfo> infos = map.get(pid);

        if (!CollectionUtils.isEmpty(infos)) {
            for (MenuInfo info : infos) {
                info.setChild(getChild(info.getId(), map));
            }
        }

        return infos;
    }
}
